package by.yativem.commons.console.devices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

import org.apache.log4j.Logger;

public class StreamConsoleDevice implements ITextDevice {
	private static final Logger log = Logger
			.getLogger(StreamConsoleDevice.class);

	private final BufferedReader reader;
	private final PrintWriter writer;

	public StreamConsoleDevice(BufferedReader reader, PrintWriter writer) {
		this.reader = reader;
		this.writer = writer;
	}
	public StreamConsoleDevice(InputStream in, OutputStream out) {
		this.reader = new BufferedReader(new  InputStreamReader( in));
		this.writer = new PrintWriter(out, true);
	}

	
	@Override
	public void write(String fmt) throws ConsoleException {
		writer.printf(fmt);
		writer.flush();

	}

	@Override
	public void write(String fmt, Object... params) throws ConsoleException {
		writer.printf(fmt, params);
		writer.flush();
	}

	@Override
	public String readLine() throws ConsoleException {
		try {
			return reader.readLine();
		} catch (IOException e) {
			throw new IllegalStateException();
		}
	}

	@Override
	public char[] readPassword() throws ConsoleException {
		return readLine().toCharArray();
	}

}
